#!/bin/bash
set -u -e -E -C -o pipefail

BUILD_HOST=${1?:BUILD_HOST not given}

if [[ -d dist ]]; then 
    DIST_DIR=dist
    VERSION=$(basename $(ls -1 $DIST_DIR/*.tar.gz | sort | tail -n 1) .tar.gz)
else
    echo "no dist dir found, aborting"
    exit 1
fi

ARTEFACT=$VERSION.tar.gz
echo "building rpm from $DIST_DIR/$ARTEFACT on $BUILD_HOST"

mkdir -p dist
ssh $BUILD_HOST "
    mkdir -p ~/build/$VERSION ~/dist 
    cd build/$VERSION
    tar zxf -

    rpmbuild --define=\"_topdir \$(pwd)/rpmbuild\" -ta $ARTEFACT >&2

    cp \$(find rpmbuild -name \*.rpm) ~/dist

    tar zcf - \$(find rpmbuild -name \*.rpm)
" < $DIST_DIR/$ARTEFACT | tar zxf - -C dist --xform s:^.*/::

